/*
 * @Author: xiaosihan 
 * @Date: 2024-08-01 15:32:26 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-26 21:45:28
 */

import shortid from "shortid";
import pathBrowserify from "path-browserify";
import queryString from 'query-string';
import SparkMD5 from "spark-md5";
import Api from "@/api/Api";
import urlparse from 'url-parse';

class Utils {

    constructor() {
        console.log("isWX", this.isWX);
        console.log("isBrowser", this.isBrowser);
        console.log("isDev", this.isDev);
        console.log("isTest", this.isTest);
        console.log("isProd", this.isProd);
    }
    // 微信小程序环境
    isWX = (typeof wx === 'object' && wx !== null);

    // 浏览器环境
    isBrowser = (!this.isWX && typeof window === 'object' && window !== null);

    // 开发环境
    isDev = (() => {
        if (this.isBrowser) {
            return (process.env.NODE_ENV === "development");
        } else if (this.isWX && typeof wx !== 'undefined' && typeof wx.getAccountInfoSync === 'function') {
            try {
                return wx.getAccountInfoSync().miniProgram.envVersion === "develop";
            } catch (e) {
                return false;
            }
        }
        return (process.env.NODE_ENV?.trim() === "development");
    })();

    // 测试环境
    isTest = (() => {
        if (this.isBrowser) {
            return (process.env.NODE_ENV?.trim() === "test");
        } else if (this.isWX && typeof wx !== 'undefined' && typeof wx.getAccountInfoSync === 'function') {
            try {
                return wx.getAccountInfoSync().miniProgram.envVersion === "trial";
            } catch (e) {
                return false;
            }
        }
        return (process.env.NODE_ENV?.trim() === "test");
    })();

    // 正式环境
    isProd = (() => {
        if (this.isBrowser) {
            return (process.env.NODE_ENV?.trim() === "production");
        } else if (this.isWX && typeof wx !== 'undefined' && typeof wx.getAccountInfoSync === 'function') {
            try {
                return wx.getAccountInfoSync().miniProgram.envVersion === "release";
            } catch (e) {
                return false;
            }
        }
        return (process.env.NODE_ENV?.trim() === "production");
    })();

    // 苹果手机
    isIPhone = this.isWX && typeof wx !== 'undefined' && typeof wx.getDeviceInfo === 'function' && wx.getDeviceInfo().brand === "iPhone";

    // 华为
    isHuawei = this.isWX && typeof wx !== 'undefined' && typeof wx.getDeviceInfo === 'function' && wx.getDeviceInfo().brand === "HUAWEI";

    // 封装本地存储设置方法
    setStorageSync(key: string, value: any) {
        if (this.isBrowser && typeof localStorage !== 'undefined') {
            localStorage.setItem(key, value);
        } else if (this.isWX && typeof wx !== 'undefined' && typeof wx.setStorageSync === 'function') {
            wx.setStorageSync(key, value);
        }
    }

    // 封装本地存储获取方法
    getStorageSync(key: string) {
        if (this.isBrowser && typeof localStorage !== 'undefined') {
            return localStorage.getItem(key);
        } else if (this.isWX && typeof wx !== 'undefined' && typeof wx.getStorageSync === 'function') {
            return wx.getStorageSync(key);
        }
    }

    // 封装本地存储删除方法
    removeStorageSync(key: string) {
        if (this.isBrowser && typeof localStorage !== 'undefined') {
            localStorage.removeItem(key);
        } else if (this.isWX && typeof wx !== 'undefined' && typeof wx.removeStorageSync === 'function') {
            wx.removeStorageSync(key);
        }
    }

    // 封装本地存储清空方法
    clearStorageSync() {
        if (this.isBrowser && typeof localStorage !== 'undefined') {
            localStorage.clear();
        } else if (this.isWX && typeof wx !== 'undefined' && typeof wx.clearStorageSync === 'function') {
            wx.clearStorageSync();
        }
    }

    // 生成短ID
    uuid() {
        const shortId = shortid();
        return shortId;
    }

    // 获取问号后参数
    getQueryString = (key: string) => {
        const parsedHash = queryString.parse(location.search);
        return parsedHash[key];
    };

    // 解析URL路径
    parseUrl(url: string) {
        const { root, dir, base, ext, name, } = pathBrowserify.parse(url);
        return { root, dir, base, ext, name };
    }

    // 获取文件指纹
    async getFileMD5(file: File) {
        return new Promise((resolve) => {
            const spark = new SparkMD5.ArrayBuffer();
            const reader = new FileReader();

            reader.onload = (e) => {
                spark.append(e.target!.result as ArrayBuffer);
                resolve(spark.end()); // 返回 MD5 哈希值
            };

            reader.readAsArrayBuffer(file);
        });
    }

    ossSuffix(src: string = "", maxSide?: number) {
        // 输入空,或者占位图,就直接返回占位图
        if (!src || src === "./UTlogo.svg") {
            return "./UTlogo.svg";
        }
        const urlParam = urlparse(src);
        let newSrc = urlParam.pathname;
        // let newSrc = (src || "")
        //     .replace(/(\?|&)(x-oss-process=.*?)(?=&|$)/, '')
        //     .replace(/^https?:/, "")
        //     .replace(Api.oss_host, "")
        if (maxSide && !src.endsWith('.svg')) {
            newSrc += `?x-oss-process=image/resize,m_lfit,w_${maxSide},h_${maxSide}`;
        }
        const resultUrl = `${Api.oss_host}${newSrc}`;
        return resultUrl;
    }

    //文件转blob
    fileToBloburl(file: File) {
        return new Promise<string>((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = function (event) {
                const arrayBuffer = event!.target!.result as ArrayBuffer;
                const blob = new Blob([arrayBuffer]);
                const bloburl = URL.createObjectURL(blob);
                resolve(bloburl);
            };
            reader.onerror = function (error) {
                throw new Error(`文件转blbo 失败,${file.name}`);
            };
            reader.readAsArrayBuffer(file);
        });
    }

    /**
     * 多选文件
     */
    async selectFiles(accept = ".jpg,.jpeg,.png,.tga"): Promise<File[]> {
        return new Promise<File[]>((resolve, reject) => {
            const input = document.createElement("input");
            input.style.display = "none";
            input.type = "file";
            input.multiple = true;
            input.accept = accept;
            input.onchange = (e: any) => {
                const files = e.target.files as unknown as Promise<File[]>;
                resolve(files);
            };
            document.body.append(input);
            input.click();
            setTimeout(() => {
                input.remove();
            }, 100);
        });
    }

    /**
     * 单选文件
     */
    async selectFile(accept = ".jpg,.jpeg,.png,.tga"): Promise<File> {
        return new Promise<File>((resolve, reject) => {
            const input = document.createElement("input");
            input.style.display = "none";
            input.type = "file";
            input.multiple = false;
            input.accept = accept;
            input.onchange = (e: any) => {
                const files = e.target.files as PromiseLike<File>;
                resolve((files as unknown as File[])[0]);
            };
            document.body.append(input);
            input.click();
            setTimeout(() => {
                input.remove();
            }, 100);
        });
    }

    /**
     * 多选文件转blob
     */
    async selectFilesToBlobs(accept = ".jpg,.jpeg,.png,.tga"): Promise<string[]> {
        const files = (await this.selectFiles(accept)) as File[];
        const bloburls: Array<string> = [];
        for (let file of files) {
            const bloburl = await this.fileToBloburl(file);
            bloburls.push(bloburl);
        }
        return bloburls;
    }

    /**
     * 单选文件转blob
     */
    async selectFileToBlob(accept = ".jpg,.jpeg,.png,.tga"): Promise<string> {
        const file = (await this.selectFile(accept)) as File;
        const bloburl = await this.fileToBloburl(file);
        return bloburl;
    }

    /**
     * 选择文件夹
     */
    async selectDirectory() {
        return new Promise<Array<File>>((resolve, reject) => {
            const input = document.createElement("input");
            input.style.display = "none";
            input.type = "file";
            input.webkitdirectory = true;
            input.onchange = (e: any) => {
                const files = e.target.files as FileList;
                resolve([...files]);
            };
            document.body.append(input);
            input.click();
            setTimeout(() => {
                input.remove();
            }, 100);
        });
    }

}
// Utils类结束

// 创建Utils实例
const utils = new Utils();
// 导出utils实例
export default utils;